<template>
    <div id="root_box">
        <div class="box">
            <div class="left_box">
                <div>
                    <el-input
                        style="width:auto"
                        prefix-icon="el-icon-search"
                        v-model.trim="state"
                        placeholder="请输入角色名称"
                        @keyup.enter.native="search"
                    ></el-input>
                </div>
                <div class="tree">
                    <el-tree
                        :data="data"
                        node-key="id"
                        draggable
                        icon-class="el-icon-arrow-right"
                        :default-expanded-keys="expandedKeys"
                        @node-click="handleNodeClick"
                        @node-drop="handleDrop"
                    >
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                            <i :class="[data.icon]"></i>
                            <span :id="[data.id]" :style="{ color: '#333' }">{{ node.label }}</span>
                        </span>
                    </el-tree>
                </div>
            </div>
            <div class="right_box">
                <div class="title">
                    <p v-if="selfId==='add'">添加角色</p>
                    <p v-else>角色详情</p>
                    <div class="edit_box" v-if="selfId!='add'" @click="toEdit">
                        <i class="el-icon-edit"></i>编辑
                    </div>
                </div>
                <div class="input_box">
                    <template v-if="selfId!='add'">
                        <!-- 编辑的input -->
                        <el-input
                            v-model.trim="form.roleName"
                            placeholder="请输入角色名称"
                            maxlength="10"
                            v-if="isEdit"
                        ></el-input>
                        <p v-else>{{ form.roleName }}</p>
                    </template>
                    <template v-if="selfId==='add'">
                        <!-- 新增的input -->
                        <el-input v-model.trim="form.roleName" placeholder="请输入角色名称" maxlength="30"></el-input>
                    </template>
                    <el-input
                        v-model.trim="form.introduction"
                        placeholder="请输入角色简介"
                        maxlength="10"
                        style="margin-left:20px;"
                    ></el-input>
                </div>
                <div class="tree_box">
                    <el-tree
                        :data="leftData"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        ref="tree"
                        highlight-current
                        :props="defaultProps"
                        :default-checked-keys="leftDataChecked"
                    ></el-tree>
                </div>
                <div class="btn_box">
                    <template v-if="selfId==='add'">
                        <div class="btn confirm" @click="addRole">确定</div>
                        <div class="btn cancel" @click="cancelRole">取消</div>
                    </template>
                    <template v-else>
                        <div class="btn confirm" v-if="isEdit" @click="editRole">确定</div>
                        <div class="btn delete" @click="deleteRole">删除</div>
                    </template>
                </div>
            </div>
            <el-dialog title="编辑角色" :visible.sync="addVisible" width="590px" margin-top="40vh">
                <p style="text-align:center">确认保存【{{form.roleName}}】？</p>
                <div class="tableBtnBox">
                    <button class="btn1" @click="cancelAdd">取消</button>
                    <button class="btn2" @click="addConfirm">确认</button>
                </div>
            </el-dialog>
            <!-- 删除弹窗 -->
            <myDialog
                :isShow="delVisible"
                title="删除角色"
                :context="`是否删除【${form.roleName}】？`"
                @cancel="cancelDel"
                @confirm="confirmDel"
            ></myDialog>
            <!-- 移动组织弹窗 -->
            <myDialog
                :isShow="removeVisible"
                title="删除组织"
                context="是否将该组织及下属组织移动到此处？"
                @cancel="concelRemove"
                @confirm="confirmRemove"
            ></myDialog>
        </div>
    </div>
</template>
<script>
import { throttle } from '@/utils/tools.js';
import { roleList, roleDetail, roleAdd, roleEdit, roleDelete, roleUpdate } from '@/api/index.js';
import myDialog from '../components/dialog.vue';
export default {
    components: {
        myDialog
    },
    data() {
        return {
            state: '',
            timeout: null,
            form: {
                roleName: '',
                introduction: '' // 角色简介
            },
            rules: {
                roleName: [{ required: true, message: '请输入角色名称', trigger: 'input' }],
                introduction: [{ required: true, message: '请输入角色简介', trigger: 'change' }]
            },
            addVisible: false,
            delVisible: false, // 删除弹窗
            data: [],
            leftData: [],
            leftDataChecked: [], // 右侧列表默认展开
            expandedKeys: [], // 左侧树默认展开的数组
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            isEdit: false,
            parentId: undefined,
            selfId: 'add',
            removeVisible: false, // 移动节点
            nodeObj: {} // node节点信息
        };
    },
    mounted() {
        this.getroleList();
        this.getroleDetail({ id: 'add' });
    },
    methods: {
        // 搜索事件
        search: throttle(function () {
            this.expandedKeys = [];
            this.getroleList();
        }, 3000),
        // 重置页面状态
        resetStuts() {
            this.getroleList();
            this.isEdit = false;
            this.selfId = 'add';
            this.leftData = [];
            this.addVisible = false;
            this.delVisible = false;
            this.form = {
                roleName: '',
                introduction: ''
            };
        },
        // 获取列表
        getroleList() {
            let that = this;
            let params = {};
            if (this.state) params.name = this.state;
            roleList(params).then((res) => {
                if (res.code === 200) {
                    if (res.result && res.result.length > 0) {
                        let list = res.result;
                        const newChild = { id: 'add', label: '添加角色', parentId: '0', icon: 'el-icon-circle-plus', children: [] };
                        list.push(newChild);
                        // 递归添加 （添加角色数据）
                        let forObj = (list) => {
                            list.forEach((row) => {
                                if (row.id != 'add') {
                                    const newChild = {
                                        id: 'add',
                                        label: '添加角色',
                                        parentId: row.id,
                                        icon: 'el-icon-circle-plus',
                                        children: []
                                    };
                                    row.children = row.children ? row.children : [];
                                    row.children.push(newChild);
                                    forObj(row.children);
                                    if (row.isMatch) that.expandedKeys.push(row.id);
                                }
                            });
                        };
                        forObj(list);
                        this.data = list;
                    }
                } else this.$message.error(res.message);
            });
        },
        //******************************点击node
        handleNodeClick(data) {
            if (data.id == 'add') {
                this.form.roleName = '';
            } else {
                this.form.roleName = data.label;
            }
            this.isEdit = false;
            this.parentId = data.parentId;
            this.selfId = data.id;
            if (!data.children) return;
            let item = data.children.find((item) => {
                return item.id == 'add';
            });
            // 每次点击都会调取详情接口
            this.getroleDetail(data);
        },
        //******************* */ 获取详情
        getroleDetail(data) {
            let params = {};
            let that = this;
            this.leftDataChecked = [];
            if (data.id !== 'add') params.roleId = data.id;
            roleDetail(params).then((res) => {
                if (res.code === 200) {
                    this.form.introduction = res.result.introduction;
                    this.form.roleName = res.result.roleName;
                    let list = res.result.functionList.map((item) => {
                        let children = [];
                        if (item.functionList && item.functionList.length > 0) {
                            children = item.functionList.map((t) => {
                                let sunList = [];
                                if (t.functionList && t.functionList.length > 0) {
                                    sunList = t.functionList.map((p) => {
                                        if (p.isCheck) that.leftDataChecked.push(p.id);
                                        return {
                                            id: p.id,
                                            label: p.functionName,
                                            disabled: data.id !== 'add' ? true : false,
                                            isCheck: p.isCheck
                                        };
                                    });
                                }
                                if (t.isCheck) that.leftDataChecked.push(t.id);
                                return {
                                    id: t.id,
                                    label: t.functionName,
                                    disabled: data.id !== 'add' ? true : false,
                                    isCheck: t.isCheck,
                                    children: sunList
                                };
                            });
                        }
                        if (item.isCheck) that.leftDataChecked.push(item.id);
                        return {
                            id: item.id,
                            label: item.functionName,
                            isCheck: item.isCheck,
                            disabled: data.id !== 'add' ? true : false,
                            children: children
                        };
                    });
                    console.log(res.result.functionList);
                    console.log(list);
                    this.leftData = list;
                } else this.$message.error(res.message);
            });
        },
        //*************************** */ 点击新增
        addRole() {
            if (!this.form.roleName) {
                this.$message.warning('请输入角色名称');
                return;
            }
            if (!this.form.introduction) {
                this.$message.warning('请输入角色简介');
                return;
            }
            let params = {
                roleName: this.form.roleName,
                introduction: this.form.introduction,
                parentId: this.parentId,
                functionIds: this.$refs.tree.getCheckedKeys()
            };
            roleAdd(params).then((res) => {
                if (res.code === 200) {
                    this.$message.success('新增成功');
                    // 重置页面状态
                    this.resetStuts();
                } else this.$message.error(res.message);
            });
        },
        // 恢复刚进来的状态
        cancelRole () {
            this.resetStuts();
            this.getroleDetail({ id: 'add' });
        },
        //************************* */ 删除角色
        deleteRole() {
            this.delVisible = true;
        },
        cancelDel() {
            this.delVisible = false;
        },
        confirmDel() {
            let params = {
                roleId: this.selfId
            };
            roleDelete(params).then((res) => {
                if (res.code === 200) {
                    this.delVisible = false;
                    this.resetStuts();
                    this.$message.success('删除成功');
                } else this.$message.error(res.message);
            });
        },
        //********************************** */ 拖拽
        handleDrop(before, after, inne, event) {
            this.removeVisible = true;
            this.nodeObj = {
                before,
                after,
                inne,
                event
            };
        },
        // 取消移动
        concelRemove() {
            this.removeVisible = false;
            this.getroleList();
        },
        // 确定移动
        confirmRemove() {
            const { before, after, inne, event } = this.nodeObj;
            let startInfo = before.data.id;
            let organizationId = after.data.parentId;
            let params = {
                targetId: organizationId,
                roleId: startInfo
            };
            roleUpdate(params).then((res) => {
                // 不管有没有成功都刷新一下列表
                if (res.code === 200) {
                    this.$message.success('移动成功');
                    this.removeVisible = false;
                    this.resetStuts();
                } else {
                    this.getroleList();
                    this.$message.error(res.message);
                }
            });
        },
        //*****************************************编辑
        toEdit() {
            this.isEdit = !this.isEdit;
            this.changeStatue(!this.isEdit);
            // this.addVisible = true;
        },
        // 确认编辑
        editRole: throttle(function () {
            this.addVisible = true;
        }, 3000),
        //取消编辑
        cancelAdd() {
            this.addVisible = false;
        },
        //编辑点击确认
        addConfirm: throttle(function () {
            if (!this.form.roleName) {
                this.$message.warning('请输入角色名称');
                return;
            }
            if (!this.form.introduction) {
                this.$message.warning('请输入角色简介');
                return;
            }
            let params = {
                roleId: this.selfId,
                roleName: this.form.roleName,
                introduction: this.form.introduction,
                functionIds: this.$refs.tree.getCheckedKeys()
            };
            roleEdit(params).then((res) => {
                if (res.code === 200) {
                    this.resetStuts();
                    this.$message.success('修改成功');
                    // 重置页面状态
                } else this.$message.error(res.message);
            });
        }, 3000),
        //******************************** */ 修改右侧的树形结构状态
        changeStatue(status) {
            this.leftData.forEach((item) => {
                item.disabled = status;
                item.children.forEach((t) => {
                    t.disabled = status;
                    if (t.children && t.children.length > 0) {
                        t.children.forEach((son) => (son.disabled = status));
                    }
                });
            });
        }
    }
};
</script>
<style lang="scss">
#root_box {
    .box {
        width: 100%;
        display: flex;
    }
    .left_box {
        width: 60%;
        height: calc(100vh - 11.25rem /* 180/16 */);
        background: #ffffff;
        box-shadow: 0px 11px 14px -10px #e5eced;
        border-radius: 5px;
        box-sizing: border-box;
        padding: 1.625rem /* 26/16 */ 1.875rem /* 30/16 */;
    }
    .right_box {
        width: 40%;
        height: calc(100vh - 11.25rem /* 180/16 */);
        background: #ffffff;
        box-shadow: 0px 11px 14px -10px #e5eced;
        border-radius: 5px;
        margin-left: 1.875rem /* 30/16 */;
        box-sizing: border-box;
        padding: 1.625rem /* 26/16 */ 1.875rem /* 30/16 */;
    }
    .tree {
        margin-top: 2.125rem /* 34/16 */;
        height: 80%;
        overflow-y: scroll;
    }
    .tree::-webkit-scrollbar {
        display: none;
    }
    .title {
        width: 100%;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 22px;
        display: flex;
    }
    .edit_box {
        margin-left: auto;
        cursor: pointer;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 22px;
        border: none;
    }
    .input_box {
        width: 24.875rem /* 398/16 */;
        height: 2.1875rem /* 35/16 */;
        margin-top: 2.125rem /* 34/16 */;
        display: flex;
        // p{
        //   width:11.8125rem /* 189/16 */;
        // }
    }
    .input_box p {
        width: 21.25rem /* 340/16 */;
    }
    .btn_box {
        width: 24.875rem /* 398/16 */;
        display: flex;
        margin-top: 1.875rem /* 30/16 */;
        justify-content: center;
        align-items: center;
    }
    .btn {
        width: 5.125rem /* 82/16 */;
        height: 2.1875rem /* 35/16 */;
        border-radius: 0.3125rem /* 5/16 */;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        line-height: 2.1875rem /* 35/16 */;
        text-align: center;
        cursor: pointer;
    }
    .confirm {
        background: #214a8f;
        color: #ffffff;
    }
    .cancel {
        color: #004fab;
        background: rgba(0, 79, 171, 0.2);
        margin-left: 5.375rem /* 86/16 */;
    }
    .delete {
        color: #ffffff;

        background: #d0021b;
        margin-left: 6.6875rem /* 107/16 */;
    }
    .newForm {
        .el-form-item {
            border-bottom: 1px solid #d8d8d8;
        }
    }
    .el-dialog__header {
        background: rgba(33, 74, 143, 0.1);
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(33, 74, 143, 1);
    }
    .el-dialog__body {
        max-height: 720px;
        // overflow-y: scroll;
        position: relative;
    }
    .el-icon-close:before {
        border-radius: 50%;
        color: #fff;
        background-color: rgba(33, 74, 143, 1);
    }
    .newForm/deep/.el-input__inner {
        border: none;
    }
    .specityBox {
        .tableBox {
            max-height: 452px;
            overflow-y: scroll;
        }
        .tableBox::-webkit-scrollbar {
            width: 0;
        }
    }
    .el-dialog__body {
        padding: 2.5rem /* 40/16 */ 0 1.25rem /* 20/16 */ 1.25rem /* 20/16 */ !important;
        padding-top: 2.5rem /* 40/16 */ !important;
        padding-bottom: 64px;
    }
    .tableBtnBox {
        margin-top: 1.875rem /* 30/16 */;
        text-align: center;
        .btn1 {
            width: 90px;
            height: 35px;
            background: rgba(0, 79, 171, 0.2);
            border-radius: 5px;
            border: none;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 79, 171, 1);
            margin-right: 56px;
            cursor: pointer;
        }
        .btn2 {
            width: 90px;
            height: 35px;
            background: rgba(0, 79, 171, 1);
            border-radius: 5px;
            border: none;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            cursor: pointer;
        }
    }
    .el-form-item__content {
        margin-left: 0 !important;
    }
    .newObjectConfirm {
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 28px;
        background: rgba(0, 79, 171, 1) !important;
    }
    .newObjectCancel {
        width: 90px !important;
        height: 35px;
        background: rgba(255, 255, 255, 0.2) !important;
        border-radius: 5px;
    }
    .el-icon-circle-plus {
        color: #214a8f;
        margin-left: -16px;
    }
    #add {
        color: #214a8f;
    }
    .tree_box {
        width: 24.875rem /* 398/16 */;
        height: 15.75rem /* 252/16 */;
        overflow: auto;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin-top: 1.875rem /* 30/16 */;
        box-sizing: border-box;
        padding-left: 0.625rem /* 10/16 */;
    }
    .tree_box .el-tree-node__expand-icon {
        display: none !important;
    }
    .tree_box .el-tree .el-icon-caret-right:before {
        content: '' !important;
    }
    .tree_box::-webkit-scrollbar {
        width: 0.3125rem /* 5/16 */;
    }
    // .tree_box::-webkit-scrollbar-track {
    //     background-color: red;
    //     -webkit-border-radius: 2em;
    //     -moz-border-radius: 2em;
    //     border-radius: 2em;
    // }
    .tree_box::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.45);
        -webkit-border-radius: 2em;
        -moz-border-radius: 2em;
        border-radius: 2em;
    }
}
.custom-tree-node{
    display: flex;
    align-items: center;
    font-family: PingFangSC-Regular, PingFang SC;
    .isDivision{
        width: 1.125rem /* 18/16 */;
        height: 1.125rem /* 18/16 */;
        margin-left: .625rem /* 10/16 */;
    }
}
</style>
